import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// import { get } from 'core-js/core/dict'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },

  // 设置用户资料
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USAERINFO: (state, data) => {
    state.userInfo = data
  }
}

// action方法
const actions = {
// 用户登录
// 异步
// TODO : 用户登录逻辑 发起登录请求、存储token
  async login({ commit }, userInfo) {
    // 读取调用该action方法时候，传入用户资料
    // 发起网络请求
    const res = await login(userInfo)
    console.log(res)
    // const { username, password } = userInfo
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })

    // 设置token
    commit('SET_TOKEN', res.token)
    // 存储到本地
    setToken(res.token)
  },

  // 获取用户资料
  // TODO：获取用户资料逻辑
  async getInfo({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { name, avatar } = data

    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
    const res = await getInfo()

    commit('SET_USAERINFO', res.userInfo)
    // 返回用户信息
    return res
  },

  // user logout
  logout({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
    removeToken() // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
    // 重置侧边栏信息
    commit('permission/setRoutes', [], { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

